/**
 @Name    工具脚本
 */
layui.define(['jquery', 'layer', 'table', 'laytpl'], function (exports) {
    "use strict";

    var $ = layui.jquery;

    var laytpl = layui.laytpl
        , layTable = layui.table
        , form = layui.form
        , layer = layui.layer
        , pLayer = parent.layui.layer ? parent.layui.layer : layer;

    /*
    if (parent.parent.layui.layer) {
        pLayer = parent.parent.layui.layer;
    } else if (parent.layui.layer) {
        pLayer = parent.layui.layer;
    } else {
        pLayer = layer;
    }
    */
    var ligutil = {

        /**弹出层（遮盖）工具类 A**/
        alert: function (message) {
            return layer.alert(message, {title: '提示', icon: 6, btn: ['知道了']});
        },
        confirm: function (message, opt, success, error) {
            if (typeof opt == 'undefined') {
                opt = {};
            }
            if (typeof opt.title == 'undefined' || opt.title == '') {
                opt.title = '提示';
            }
            open
            opt.icon = 3;
            return pLayer.confirm(message, opt, success, error);
        },
        msg: function (message) {
            layer.msg(message, {icon: 0, time: 1500});
        },
        error: function (message) {
            pLayer.alert(message, {title: '提示', icon: 5, btn: ['知道了']});
        },
        success: function (message) {
            if (typeof message == 'undefined' || message == '') {
                message = '操作成功！';
            }
            layer.msg(message, {icon: 1, time: 1500, offset: 't'});
        },
        fail: function (message) {
            pLayer.alert(message, {icon: 5});
        },
        open: function (html, option) {
            var _self = this;

            var _width = $(document).width() + 'px'
                , _height = 'auto'
                , _title = ''
                , _type = 1
                , _success = function () {
            }
                , _end = function () {
            };
            if (typeof option != 'undefined') {
                if (typeof option.title != 'undefined' && option.title != '') {
                    _title = option.title;
                }
                if (typeof option.width != 'undefined' && option.width != '') {
                    _width = option.width + 'px';
                }
                if (typeof option.height != 'undefined' && option.height != '') {
                    _height = option.height + 'px';
                }
                if (typeof option.type != 'undefined' && option.type != '') {
                    _type = option.type;
                }
                if (typeof option.end != 'undefined' && typeof option.end == 'function') {
                    _end = option.end;
                }
                if (typeof option.success != 'undefined' && typeof option.success == 'function') {
                    _success = option.success;
                }
            }

            if ($('#layer_return_data').length <= 0) {
                $(document.body).append('<input type="hidden" id="layer_return_data">');
            }

            return layer.open({
                type: _type
                , offset: 't'
                , closeBtn: 0
                //,anim: 2
                , title: _title
                , area: [_width, _height] //宽高
                , content: html
                , success: function (layero, index) {
                    _success(layero, index);
                }
                , end: function () {
                    var _data = _self.getLayerReturnData();
                    _end(_data);
                }
            });
        }
        , remove: function (options) {
            var _self = this;

            var _layerIndex = _self.confirm('确定删除吗？',
                {
                    btn: ['确定', '取消']
                }
                , function () {
                    _self.ajaxpost({
                        url: options.url,
                        data: options.data,
                        success: function (result) {
                            if (result.success) {
                                _self.success('删除成功！');
                                if (typeof options.completed != 'undefined') {
                                    options.completed();
                                }
                            } else {
                                _self.error(result.message);
                            }
                            _self.closeLayer(_layerIndex);
                        }
                    });
                }
                , function () {
                    // 取消操作
                    if (typeof options.cancel != 'undefined') {
                        options.cancel();
                    }
                }
            );
            return _layerIndex;
        }
        /**
         * 删除弹出层
         * @param index
         */
        , close: function (index) {
            if (typeof index == 'undefined') {
                index = layer.getFrameIndex(window.name);
            }
            layer.close(index);
        }
        /**
         * 删除父级的弹出层
         * @param index
         */
        , closeLayer: function (index) {
            if (typeof index == 'undefined') {
                index = pLayer.getFrameIndex(window.name);
            }
            pLayer.close(index);
        }
        , setLayerReturnData: function (data) {
            if (typeof data != 'undefined' && typeof data == 'object') {
                data = JSON.stringify(data);
            }
            return parent.$('#layer_return_data').val(data);
        }
        , getLayerReturnData: function () {
            var _self = this;

            var _data = $('#layer_return_data').val();
            if (_self.isJSON(_data)) {
                return $.parseJSON(_data);
            }
            return '';
        }
        /**弹出层（遮盖）工具类 Z**/



        /**table工具类 A**/
        /**封装layui grid**/
        , table: function (options, extend) {
            var _self = this;

            if (typeof options == 'undefined') {
                return;
            }

            if (typeof options.height == 'undefined') {
                options.height = 'full-100';
            }

            if (typeof options.page == 'undefined') {
                options.page = {theme: '#409EFF'};//开启分页,
            }
            options.request = {
                pageName: 'pageNum' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            };
            options.response = {
                statusName: 'code' //数据状态的字段名称，默认：generator
                , statusCode: 200 //成功的状态码，默认：0
                , msgName: 'message' //状态信息的字段名称，默认：msg
                , countName: 'count' //数据总数的字段名称，默认：count
                , dataName: 'data' //数据列表的字段名称，默认：data
            };
            options.parseData = function (res) { //res 即为原始返回的数据
                var _code = res.success ? 200 : 500
                    , _count = res.data ? res.data.total : 0
                    , _data = res.data ? res.data.items : null;
                return {
                    "code": _code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": _count, //解析数据长度
                    "data": _data //解析数据列表
                };
            }
            // 表格数据加载完成
            if (typeof options.done != 'undefined'
                && typeof options.done == 'function') {
                options.done = options.done;
            }

            options.limit = 30;
            options.id = 'idTest';
            options.defaultToolbar = ['filter', 'print'];
            //options.skin = 'line';
            //options.even = true;
            var _table = layTable.render(options);

            if (typeof options.toolEvent != 'undefined'
                && typeof options.toolEvent == 'function') {
                table.on('tool', function (obj) {
                    options.toolEvent(obj);
                });
            }

            //监听表格复选框选择
            if (typeof options.checkboxEvent != 'undefined'
                && typeof options.checkboxEvent == 'function') {
                table.on('checkbox(' + options.id + ')', function (obj) {
                    options.checkboxEvent(obj);
                });
            }

            var _reloadTable = function () {
                var _dataJSON = _self.form2JSON('.lig-searchform');
                _table.reload({
                    where: _dataJSON
                    , done: function () {
                        _self._tableExtend(_table, extend);
                    }
                });
            }
            _table.reloadTable = _reloadTable;


            if (arguments.length = 2) {
                _self._tableExtend(_table, extend);
            }

            return _table;
        },
        _tableExtend: function (dataTable, extend) {
            var _self = this
                , _layerIndex;

            var _cancel = function () {
                $('.ligui-cancel').unbind('click').bind('click', function () {
                    _self.close(_layerIndex);
                });
            };

            // 保存
            var _save = function (url) {
                // 监听提交
                form.on('submit(lig-save)', function (data) {
                    _self.ajaxpost({
                        url: ctx + url
                        , data: data.field
                        , success: function () {
                            dataTable.reloadTable();
                            _self.close(_layerIndex);
                            _self.success();
                        }
                    });
                    return false;
                });
            };

            // 删除
            var _remove = function () {
                var _datas = layTable.checkStatus('idTest').data
                    , _length = _datas.length;
                if (_length <= 0) {
                    return;
                }

                var _ids = '';
                $.each(_datas, function (i, item) {
                    _ids += "," + item[extend.primaryField];
                });
                if (_ids != '') {
                    _ids = _ids.substring(1);
                }
                _self.remove({
                    url: extend.removeUrl
                    , data: {ids: _ids}
                    , completed: function () {
                        dataTable.reloadTable();
                    }
                });
            };

            // 获取详情
            var _get = function (id, callbaock) {
                var _data = {};

                var _url = extend.getUrl,
                    _p = '{' + extend.primaryField + '}';

                if (_url.indexOf(_p) > -1) {
                    _url = _url.replace(_p, id);
                } else {
                    _data[extend.primaryField] = id;
                }

                _self.ajaxget({
                    url: ctx + _url
                    , data: _data
                    , success: function (result) {
                        callbaock(result.data);
                    }
                });
            };

            // 新增
            $('.lig-add').unbind('click').bind('click', function () {
                _layerIndex = _self.open(extend.addContent,
                    {
                        type: 1
                        , title: extend.addTitle
                        , height: extend.addHeight
                        , success: function () {

                            if (typeof extend.onAddOpened != 'undefined') {
                                extend.onAddOpened();
                            }

                            _save(extend.addUrl);
                            _cancel();
                        }
                    });
            });

            // 查询
            $('.lig-search').unbind('click').bind('click', function () {
                dataTable.reloadTable();
            });

            // 行工具条
            layTable.on('tool(lig-table)', function (obj) {
                var _item = obj.data;

                switch (obj.event) {
                    case 'lig-modify':

                        _get(_item[extend.primaryField], function (data) {
                            laytpl(extend.modifyContent).render(data, function (html) {
                                _layerIndex = _self.open(html,
                                    {
                                        type: 1
                                        , title: extend.modifyTitle
                                        , height: extend.modifyHeight
                                        , success: function () {
                                            if (typeof extend.onModifyOpened != 'undefined') {
                                                extend.onModifyOpened();
                                            }
                                            _save(extend.modifyUrl);
                                            _cancel();
                                        }
                                    });
                            });

                        });

                        break;
                    default:
                        if (typeof extend.onTool != 'undefined') {
                            extend.onTool(obj);
                        }
                        break;
                }
                ;
            });

            // 表格工具条
            layTable.on('toolbar(lig-table)', function (obj) {
                switch (obj.event) {
                    case 'lig-remove':
                        // 删除
                        _remove();
                        break;
                    default:
                        if (typeof extend.onTool != 'undefined') {
                            extend.onTool(obj);
                        }
                        break;
                }
                ;
            });

            $('.layui-icon-export').unbind('click').bind('click', function () {
                console.info('------');
            });
        },
        selectedRows: function (tableId) {
            return table.checkStatus(tableId);
        },
        /**table工具类 Z**/

        /**ajax工具类 A**/
        ajaxpost: function (option) {
            var _self = this;

            option.type = 'post';
            _self.ajaxaction(option);
        },
        ajaxget: function (option) {
            var _self = this;

            option.type = 'get';
            _self.ajaxaction(option);
        },
        ajaxput: function (option) {
            var _self = this;

            option.type = 'put';
            _self.ajaxaction(option);
        }
        , ajaxdelete: function (option) {
            var _self = this;

            option.type = 'delete';
            _self.ajaxaction(option);
        }
        , ajaxaction: function (option) {
            var _self = this;

            var _async = true;
            if (typeof option.async != 'undefined') {
                _async = option.async;
            }
            var _data = typeof option.data != 'undefined' ? option.data : {};
            $.ajax({
                type: option.type,
                dataType: 'json',
                async: _async,
                url: option.url,
                data: _data,
                success: function (result) {
                    if (result.success) {
                        option.success(result);
                    } else {
                        _self.error(result.message)
                    }
                },
                error: function () {
                }
            });
        }
        /**ajax工具类 Z**/

        /** 事件绑定 A**/

        /**
         * 绑定键盘事件
         * @param callback    回调函数
         */
        , keydown: function (callback) {
            $(document).keydown(function (event) {
                callback(event.keyCode);
            });
        }
        /** 事件绑定 Z**/

        , isJSON: function (jsonStr) {
            if (typeof jsonStr == 'string') {
                try {
                    var obj = JSON.parse(jsonStr);
                    return true;
                } catch (e) {
                    return false;
                }
            }
        }

        , form2JSON: function (elem) {
            var _dataJSON = {};
            $(elem).find('input,select,textarea').each(function () {
                var _this = $(this)
                    , _n = _this.attr('name')
                    , _v = _this.val();

                if (typeof _n == 'undefined') {
                    return true;
                }

                _dataJSON[_n] = _v;
            });
            return _dataJSON;
        }
    };

    // 暴露接口
    exports('ligutil', ligutil);
});